package com.blog.backend.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.blog.backend.config.CodeMsg;
import com.blog.backend.exception.GlobalException;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class AuthUtils {

    public  static String SECRET="E6D8D249BFF6AB24DE95";

    public static int pastTime=4*60*60;

    public static String createToken(String userName,String userId) throws Exception{
        //签发时间
        Date date = new Date();
        //过期时间,2小时过期
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,pastTime);
        Date expireTime = instance.getTime();
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("alg","HS256");
        map.put("typ","JWT");
        String token = JWT.create()
                .withHeader(map)
                .withClaim("userName", userName)
                .withClaim("userId", userId)
                .withExpiresAt(expireTime) //设置过期时间
                .withIssuedAt(date) //设置签发时间
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 解密token,并返回对应的用户id
     */
    public static String verifyToken(String token) throws Exception{
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt=null;
        try {
             jwt = verifier.verify(token);
        }catch (Exception e){
            throw new GlobalException(CodeMsg.LOGIN_INFO_EXPIRED);
        }
        Map<String, Claim> claims = jwt.getClaims();
        String userId = claims.get("userId").asString();
        return userId;
    }
}
